//
//  HJNetworkTools.swift
//  Swift网络工具封装
//
//  Created by 夏航军 on 16/9/24.
//  Copyright © 2016年 夏航军. All rights reserved.
//

import UIKit
import AFNetworking

//这种方法声明枚举值没有默认值
enum HTTPMethod {
   case GET
   case POST
}

class HJNetworkTools: AFHTTPSessionManager {

    //Mark:声明单例对象
    static let sharedTool :HJNetworkTools = {
       
        let tools = HJNetworkTools()
        
        //tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/html") as? Set<String>
        
         tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
        
    }()
    
    //封装核心的方法
    func request(method : HTTPMethod , urlString : String ,parameters: Any? , finished : @escaping (Any? , Error?) -> ()) {
        
        //成功闭包
        let successCallBack = {(task : URLSessionDataTask, responseObject : Any?) -> () in
            //这里需要用到参数,所以上面写了参数
            finished(responseObject, nil)

        }
        //失败的回调
        let failureCallBack = { (task: URLSessionDataTask?, error: Error) -> () in
            //输出错误信息
            print(error)
            finished(nil, error)
        }
        if method == .GET{
        
             get(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }else{
            post(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }
        
    }
    
    
}
